<?php
include_once 'application/application.php';

class Page_objtypes {



    public $action;
    public $error;



    public function __construct() {
        $this->action = Arr::getValue($_POST, 'action', false);

        DB::connect();
        if (!DB::state()) {
            $this->error = DB::getError();
        }
    }

    public function __destruct() {

    }


    public function addItem() {
        $params = array();
        $J = new JSON();
        $action = $J->readVar('action');
        $params['name'] = mysql_escape_string($J->readVar('ot_name'));
        $params['datatype'] = (int)$J->readVar('ot_datatype');


        if ($this->error) {
            $J->error($this->error);
            return $J;
        }

        if (!$params['name']) {
            $J->error('Укажите имя ');
            return $J;
        }

        if (!$params['datatype']) {
            $J->error('Укажите тип данных ');
            return $J;
        }

        $res = DB::query("SELECT id FROM `admin_objtypes` WHERE name = '{$params['name']}'");
        if (!$res || !DB::state()) {
            $J->error('Ошибка при работе с базой данных');
            return $J;
        }
        if ($res->num_rows) {
            $J->error('Такой тип объекта уже зарегистрирован');
            return $J;
        }

        $q = "INSERT INTO `admin_objtypes`
                      (`id`, `name`,`datatype` )
              VALUES  (NULL, '{$params['name']}', '{$params['datatype']}')";
        $res = DB::query($q);
        if (!$res || !DB::state()) $J->error('Ошибка при сохранении данных <!--'.DB::$mysqli->error.'-->');
        else $J->insertedId = DB::$mysqli->insert_id;

        $params['id'] = $J->insertedId;
        if (class_exists('Log')) Log::Save(OPERATION::CREATE_OBJTYPE, $params);

        return $J;
    }






    public function itemList() {
        //if ($this->error) $this->printOut ($this->error);

        $params = array();

        $params['obj_types'] = getObjTypes();;
        $params['error'] = $this->error;

        $this->printOut(includeFile(APP_PAGE_PARTS.'list_objtypes.php', $params));
    }







    public function printOut( $content = '' ) {

        include_once APP_PAGE_PARTS.'header.php';
        echo Navbar::getHorisontalBar();
        echo Auth::loginForm(true);

        $params = array(
            'leftmenu'  => Navbar::getVerticalBar('leftmenu'),//includeFile(APP_PAGE_PARTS.'leftmenu.php'),
            'content'   => $content? $content : ''
        );
        include APP_PAGE_PARTS.'columns.php';

        include_once APP_PAGE_PARTS.'footer.php';
        die();
    }



}

$page = new Page_objtypes();

if ($page->action) {
    if ($page->action == ACTIONS::INSTALL_ADD_OBJTYPE) echo $page->addItem();

}
else  {
    if (!Auth::isLogged()) reLocate ('index.php');
    Navbar::$expanded = 'lm-manager';
    Navbar::$active = 'list_objtypes';
    $page->appList();
}
?>